package com.gzdh.device.system.dto;

import cn.hutool.core.collection.CollectionUtil;
import com.gzdh.device.system.entity.SysPermission;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


@Data
public class SysUserDetailsDTO implements UserDetails {

    private String id;
    private String userName;

    private String password;

    private String nickName;
    private Integer institutionId;
    private Integer userType;

    private Integer status;

    public Collection<SimpleGrantedAuthority> authorities;

    private Set<String> perms;

    private List<SysPermission> permissions;

    public SysUserDetailsDTO() {

    }


    public SysUserDetailsDTO(UserAuthInfoDTO user) {
        this.id = user.getId();
        Set<String> roles = user.getRoles();
        Set<SimpleGrantedAuthority> authorities;
        if (CollectionUtil.isNotEmpty(roles)) {
            authorities = roles.stream()
                    .map(role -> new SimpleGrantedAuthority("ROLE_" + role)) // 标识角色
                    .collect(Collectors.toSet());
        } else {
            authorities = Collections.EMPTY_SET;
        }
        this.authorities = authorities;
        this.userName = user.getUserName();
        this.password = user.getPassword();
        this.perms = user.getPerms();
        this.userType = user.getUserType();
        this.nickName = user.getNickName();
        this.permissions = user.getPermissions();
        this.status = user.getStatus();
    }

    @Override
    public String getUsername() {
        return userName;
    }

    /**
     * 账户是否过期
     *
     * @return
     */
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    /**
     * 账户是否锁定
     *
     * @return
     */
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    /**
     * 是否启用
     *
     * @return
     */
    @Override
    public boolean isEnabled() {
        return status == 0;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return this.authorities;
    }


}